package com.yachang.qym.usbhost.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.github.nkzawa.emitter.Emitter;
import com.google.gson.Gson;
import com.yachang.qym.usbhost.R;
import com.yachang.qym.usbhost.model.MessageModel;
import com.yachang.qym.usbhost.model.RoomModel;
import com.yachang.qym.usbhost.service.LocationService;
import com.yachang.qym.usbhost.utils.AllData;
import com.yachang.qym.usbhost.utils.MessageCache;
import com.yachang.qym.usbhost.utils.SendData;
import com.yachang.qym.usbhost.utils.StringUtils;
import com.yachang.qym.usbhost.utils.ToastUtil;

import org.json.JSONObject;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

import static com.yachang.qym.usbhost.utils.API.mSocket;

public class MessageActivity extends AppCompatActivity {

    private Bitmap bitmap;
    private String senderName;
    private String mid;
    private String uid;
    private String senderOid;

    @InjectView(R.id.scrollView)
    ScrollView scrollView;
    @InjectView(R.id.toolbar)
    Toolbar toolbar;
    @InjectView(R.id.msg_list)
    LinearLayout msgList;
    @InjectView(R.id.et_msg)
    EditText etMsg;

    private Emitter.Listener onGetMessage = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
            MessageActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    MessageModel data = new MessageModel();
                    Gson gson = new Gson();
                    JSONObject jsonObject = (JSONObject) args[0];
                    data = gson.fromJson(String.valueOf(jsonObject), MessageModel.class);
                    if (data.getSenderId().equals(senderOid)) {
                        View view = LayoutInflater.from(MessageActivity.this).inflate(R.layout.item_get_message, null);
                        TextView contentText = (TextView) view.findViewById(R.id.tv_my_msg);
                        CircleImageView ivHead = (CircleImageView) view.findViewById(R.id.iv_head);
                        TextView time = (TextView) view.findViewById(R.id.time);
                        TextView name = (TextView) view.findViewById(R.id.tv_name);
                        contentText.setText(data.getMsg());
                        Calendar c = Calendar.getInstance();
                        int hour = c.get(Calendar.HOUR);
                        int minute = c.get(Calendar.MINUTE);
                        time.setText(hour + ":" + minute);
                        ivHead.setImageBitmap(bitmap);
                        name.setText(data.getSenderName());
                        msgList.addView(view);
                        scrollView.fullScroll(ScrollView.FOCUS_DOWN);
                    }
                }
            });
        }
    };

    private Emitter.Listener onGetVideo = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
            MessageActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    RoomModel data = new RoomModel();
                    Gson gson = new Gson();
                    JSONObject jsonObject = (JSONObject) args[0];
                    data = gson.fromJson(String.valueOf(jsonObject), RoomModel.class);
                    String roomId = data.getRoomId();
//                    if(roomId.equals("#####")){
//                        ToastUtil.showToast("您不是搜救者，不能开启视频通话！");
//                    }
                }
            });
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message);
        ButterKnife.inject(this);
        mSocket.on("message", onGetMessage);
        mSocket.on("video", onGetVideo);
        Intent intent = getIntent();
        senderOid = intent.getStringExtra("senderId");
        senderName = intent.getStringExtra("senderName");
        uid = intent.getStringExtra("senderUid");
        String mid = intent.getStringExtra("senderMid");
        bitmap = AllData.userBitmap.get(uid);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle(senderName);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        initData();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    private void initData(){
        List<MessageModel> list = MessageCache.msg.get(uid);
        for(MessageModel model: list){
            if(model.getSenderId().equals(senderOid)){
                View view = LayoutInflater.from(MessageActivity.this).inflate(R.layout.item_get_message, null);
                TextView contentText = (TextView) view.findViewById(R.id.tv_my_msg);
                CircleImageView ivHead = (CircleImageView) view.findViewById(R.id.iv_head);
                TextView time = (TextView) view.findViewById(R.id.time);
                TextView name = (TextView) view.findViewById(R.id.tv_name);
                contentText.setText(model.getMsg());
                Calendar c = Calendar.getInstance();
                int hour = c.get(Calendar.HOUR);
                int minute = c.get(Calendar.MINUTE);
                time.setText(hour + ":" + minute);
                ivHead.setImageBitmap(bitmap);
                name.setText(model.getSenderName());
                msgList.addView(view);
                scrollView.fullScroll(ScrollView.FOCUS_DOWN);
            } else {
                View myInfo = LayoutInflater.from(MessageActivity.this).inflate(R.layout.item_send_message, null);
                TextView contentText = (TextView) myInfo.findViewById(R.id.tv_my_msg);
                CircleImageView ivHead = (CircleImageView) myInfo.findViewById(R.id.iv_head);
                TextView time = (TextView) myInfo.findViewById(R.id.time);
                TextView name = (TextView) myInfo.findViewById(R.id.tv_name);
                contentText.setText(model.getMsg());
                Calendar c = Calendar.getInstance();
                int hour = c.get(Calendar.HOUR);
                int minute = c.get(Calendar.MINUTE);
                time.setText(hour + ":" + minute);
                ivHead.setImageBitmap(AllData.userBitmap.get(AllData.userModel.get_id()));
                name.setText(AllData.userModel.getUsername());
                msgList.addView(myInfo);
                scrollView.fullScroll(ScrollView.FOCUS_DOWN);
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_message, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home: {
                MessageActivity.this.finish();
            }break;
            case R.id.menu_deploy: {
                new AlertDialog.Builder(MessageActivity.this).setTitle("临时重组").setIcon(R.drawable.icon).setMessage("确定与 " + senderName + " 临时重组？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                SendData.data = SendData.sendContactCall(SendData.int2byte(Integer.parseInt(mid)));
                                SendData.needSend = true;
                                dialog.dismiss();
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).show();
            }break;
            case R.id.menu_video:{
                String roomId = StringUtils.getRandomString(15);
                Map<String, Object> map = new HashMap<>();
                map.put("soid", AllData.outPolice_id);
                map.put("goid", senderOid);
                map.put("roomId", roomId);
                JSONObject jsonObject = new JSONObject(map);
                mSocket.emit("video", jsonObject);

                View contentView = LayoutInflater.from(MessageActivity.this).inflate(R.layout.popup_one_item, null);
                TextView text = (TextView) contentView.findViewById(R.id.tv_main_text);
                text.setText("您开启了远程视频！");
                msgList.addView(contentView);
            }break;
        }
        return super.onOptionsItemSelected(item);
    }



    @OnClick(R.id.iv_more)
    public void btnMore(View view) {

    }


    @OnClick(R.id.iv_send)
    public void btnSend(View view) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("msg", etMsg.getText().toString());
        map.put("soid", AllData.outPolice_id);
        map.put("goid", senderOid);
        map.put("senderName", AllData.userModel.getUsername());

        //缓存聊天信息
        MessageModel model = new MessageModel();
        model.setMsg((String) map.get("msg"));
        model.setImage(AllData.userModel.getImageUrl());
        model.setSenderId(AllData.outPolice_id);
        model.setSenderName(AllData.userModel.getUsername());
        MessageCache.msg.get(uid).add(model);

        //发送数据到服务器
        JSONObject jsonObject = new JSONObject(map);
        mSocket.emit("message", jsonObject);

        View myInfo = LayoutInflater.from(MessageActivity.this).inflate(R.layout.item_send_message, null);
        TextView contentText = (TextView) myInfo.findViewById(R.id.tv_my_msg);
        CircleImageView ivHead = (CircleImageView) myInfo.findViewById(R.id.iv_head);
        TextView time = (TextView) myInfo.findViewById(R.id.time);
        TextView name = (TextView) myInfo.findViewById(R.id.tv_name);
        contentText.setText(etMsg.getText().toString());
        Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR);
        int minute = c.get(Calendar.MINUTE);
        time.setText(hour + ":" + minute);
        ivHead.setImageBitmap(AllData.userBitmap.get(AllData.userModel.get_id()));
        name.setText(AllData.userModel.getUsername());
        msgList.addView(myInfo);
        scrollView.fullScroll(ScrollView.FOCUS_DOWN);
        etMsg.setText("");
    }
}
